package org.authentication.server.config;


import org.authentication.server.handler.OAuthenticationFailureHandler;
import org.authentication.server.handler.OAuthenticationSucessHandler;
import org.authentication.server.validate.smscode.SmsAuthenticationConfig;
import org.authentication.server.validate.smscode.SmsCodeFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


@Configuration 
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter{

	@Autowired
	private OAuthenticationFailureHandler  oAuthenticationFailureHandler;
	@Autowired
	private OAuthenticationSucessHandler oAuthenticationSucessHandler;
	
	 @Autowired
	    private SmsCodeFilter smsCodeFilter;
	    @Autowired
	    private SmsAuthenticationConfig smsAuthenticationConfig;
	    /**
	     * 资源服务器认证的配置：
	     * 1、设置资源服务器的标识，从配置文件中读取自定义资源名称
	     * 2、设置Access Token的数据源(默认内存中)，本项目使用 redis，所以需要配置
	     * @param resources
	     */
	@Override
	public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
		// TODO Auto-generated method stub
		super.configure(resources);
	}

	@Override
	public void configure(HttpSecurity http) throws Exception {
		http.addFilterBefore(smsCodeFilter, UsernamePasswordAuthenticationFilter.class)   // 添加短信验证码校验过滤器
				.formLogin()  //表单登录
				.loginProcessingUrl("/login") // 处理表单登录 URL
				.successHandler(oAuthenticationSucessHandler)  //处理登录成功
				.failureHandler(oAuthenticationFailureHandler)
			.and()
				.authorizeRequests()  //授权配置
				.antMatchers("/code/sms").permitAll()   //任何用户可以访问以 code/sms开头
				.anyRequest()  //所有请求  任何没有匹配上的其他的url请求，只需要用户被验证。
				.authenticated() //都需要认证
			.and()
				.csrf().disable()
			.apply(smsAuthenticationConfig);
		
	}

	
	
	
	
	
}
